package com.gec.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gec.common.R;
import com.gec.dto.LoginUser;
import com.gec.entity.User;
import com.gec.mapper.UserMapper;
import com.gec.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpSession;

/**
 * <p>
 *
 * </p>
 *
 * @author : [chenxys]
 * @version : [v1.0]
 * @createTime : [2022/7/14 20:03]
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public User login(LoginUser loginUser, HttpSession session) {
        // 获取手机号
        String phone = loginUser.getPhone();
        // 获取验证码
        String code = loginUser.getCode();
        // 从redis中获取验证码
        // 获取验证码
        //String sessionCode = (String) session.getAttribute("code");
        String redisCode = (String) redisTemplate.opsForValue().get(phone);
        // 非空 比较
        if (StringUtils.isNotEmpty(redisCode) && redisCode.equals(code)){
            // 构造查询条件
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getPhone,phone);
            // 查询
            User user = this.getOne(userLambdaQueryWrapper);
            // 用户为空
            if (ObjectUtils.isEmpty(user)){
                // 注册为新用户
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                this.save(user);
            }
            // 登录成功,删除redis中缓存的验证码
            return user;
        }
        return null;
    }
}
